//
//  WYCRegisterController.m
//  51信用卡
//
//  Created by 中企互联 on 2017/11/3.
//  Copyright © 2017年 中企互联. All rights reserved.
//

#import "WYCRegisterController.h"
#import "UIButton+CountDown.h"
#import "WYCRealnameController.h"
#import "RSAUtil.h"
#import "QRScanViewController.h"
#import "WYCArgeeViewController.h"
#import "UIViewController+HUD.h"
@interface WYCRegisterController ()<QRScanDelegate>

/** 账号输入框*/
@property(nonatomic,strong)UITextField * UserTextField;

/** 密码*/
@property(nonatomic,strong)UITextField * passtexfield;


/** 再次输入密码*/
@property(nonatomic,strong)UITextField * Zpasstexfield;

/** 验证码*/
@property(nonatomic,strong)UITextField * codeTexField;


/** 邀请码*/
@property(nonatomic,strong)UITextField * Rgscodefield;

/** 密码隐藏或显示*/
@property(nonatomic,strong)UIButton * ZpasstexfieldButton;

/** 密码隐藏或显示*/
@property(nonatomic,strong)UIButton * passtexfieldButton;

@end

@implementation WYCRegisterController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //创建界面
    [self setupCreat];
    
}
#pragma make ------->>创建界面
- (void)setupCreat{
    
    self.view.backgroundColor = wycwhiteColor;
    
    
    //不是Nav。所以自己写的View和label
    UILabel * NavRigsterLabel = [[UILabel alloc] init];
    NavRigsterLabel.frame = CGRectMake(ScreenWidth / 2 - 100, NavHeight+30, 200, 40);
    if (ScreenHeight == 568) {
        NavRigsterLabel.frame = CGRectMake(ScreenWidth / 2 - 100, NavHeight, 200, 40);

    }
    NSLog(@"设备高%f",ScreenHeight);
    NavRigsterLabel.textColor = wycMain;
    NavRigsterLabel.font = [UIFont boldSystemFontOfSize:40];
    NavRigsterLabel.textAlignment = NSTextAlignmentCenter;
    NavRigsterLabel.text = @"注册";
    [self.view addSubview:NavRigsterLabel];
    
    
    
    //返回按钮
    UIButton *  backbutton = [[UIButton alloc] init];
    [backbutton setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    [backbutton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    backbutton.frame = CGRectMake(ScreenWidth-50, NavHeight, 33, 33);
    [self.view addSubview:backbutton];
    

    
    NSArray  *imageArr = @[@"icon_phone",@"icon_code",@"icon_password",@"icon_password",@"icon_friend"];
    NSArray  *titleArr = @[@"请输入手机号",@"请输入验证码",@"请输入密码",@"请再次输入密码",@"请输入邀请码"];
    
    for (int i = 0; i<imageArr.count; i++)
    {
        
        UIView * phoneView = [[UIView alloc] init];
        phoneView.frame = CGRectMake(40 , CGRectGetMaxY(NavRigsterLabel.frame) + 80 * px+50*i, ScreenWidth-80, 40);
        phoneView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:phoneView];
        //手机号
        UIImageView *noticeimageView = [[UIImageView alloc] init];
        noticeimageView.frame = CGRectMake(10, 8, 25, 25 );
        noticeimageView.image = [UIImage imageNamed:[imageArr objectAtIndex:i]];
        [phoneView addSubview:noticeimageView];

        UITextField * userTextField = [[UITextField alloc] init];
        userTextField.frame = CGRectMake(CGRectGetMaxX(noticeimageView.frame) + 40 * px,10, phoneView.width-60, 20);
        userTextField.backgroundColor = [UIColor clearColor];
        userTextField.placeholder = [titleArr objectAtIndex:i];
        userTextField.tintColor = wycMain;
        userTextField.font = [UIFont systemFontOfSize:15];
        [phoneView addSubview:userTextField];
        UIView  *lin =[[UIView alloc]init];
        lin.frame = CGRectMake(40, 39,phoneView.width-40, 1);
        lin.backgroundColor = WYCbgColor;
        [phoneView addSubview:lin];
        if (i==0) {
                  userTextField.clearButtonMode=UITextFieldViewModeAlways;
            userTextField.keyboardType = UIKeyboardTypeNumberPad;

            self.UserTextField = userTextField;

        }
        if (i== 1) {
                //获取验证码
                UIButton * codebutton = [[UIButton alloc] init];
                codebutton.frame = CGRectMake(phoneView.width-100,10, 100, 20);
                [codebutton setTitleColor:wycMain forState:UIControlStateNormal];
                codebutton.titleLabel.font = [UIFont systemFontOfSize:SmallFont];
                [codebutton setTitle:@"获取验证码" forState:UIControlStateNormal];
                [codebutton addTarget:self action:@selector(countDownBtnAction:) forControlEvents:UIControlEventTouchUpInside];
                [phoneView addSubview:codebutton];
            userTextField.keyboardType = UIKeyboardTypeNumberPad;

            self.codeTexField = userTextField;

        }
        if (i == 2) {
            userTextField.secureTextEntry = YES;

                UIButton * passtexfieldButton = [[UIButton alloc] init];
                passtexfieldButton.frame = CGRectMake(phoneView.width-50 , 0, 40, 40);
                [passtexfieldButton addTarget:self action:@selector(passtexfieldButtonClick) forControlEvents:UIControlEventTouchUpInside];
                [passtexfieldButton setImage:[UIImage imageNamed:@"隐藏"] forState:UIControlStateNormal];
                [passtexfieldButton setImage:[UIImage imageNamed:@"展示"] forState:UIControlStateSelected];
                [phoneView addSubview:passtexfieldButton];
                self.passtexfieldButton = passtexfieldButton;
            self.passtexfield = userTextField;

        }
        if (i == 3) {
            userTextField.secureTextEntry = YES;

            UIButton * passtexfieldButton = [[UIButton alloc] init];
            passtexfieldButton.frame = CGRectMake(phoneView.width-50 , 0, 40, 40);
            [passtexfieldButton addTarget:self action:@selector(ZpasstexfieldButtonClick) forControlEvents:UIControlEventTouchUpInside];
            [passtexfieldButton setImage:[UIImage imageNamed:@"隐藏"] forState:UIControlStateNormal];
            [passtexfieldButton setImage:[UIImage imageNamed:@"展示"] forState:UIControlStateSelected];
            [phoneView addSubview:passtexfieldButton];
            self.ZpasstexfieldButton = passtexfieldButton;
            self.Zpasstexfield = userTextField;
            
        }
//        if (i==4) {
//                UIButton * RgscodefieldButton = [[UIButton alloc] init];
//                RgscodefieldButton.frame = CGRectMake(phoneView.width-50, 0, 40,40);
//                [RgscodefieldButton addTarget:self action:@selector(rgscodeButtonClick) forControlEvents:UIControlEventTouchUpInside];
//                [RgscodefieldButton setImage:[UIImage imageNamed:@"scanning"] forState:UIControlStateNormal];
//                [phoneView addSubview:RgscodefieldButton];
//            self.Rgscodefield = userTextField;
//
//        }
        
    }
    
    //注册按钮
    UIButton * loginButton = [[UIButton alloc] init];
    loginButton.frame = CGRectMake(80 * px, 420, ScreenWidth-160*px, 150 * px);
    loginButton.backgroundColor = wycMain;
    loginButton.layer.cornerRadius = 3;
    [loginButton setTitle:@"下一步" forState:UIControlStateNormal];
    loginButton.titleLabel.font = [UIFont systemFontOfSize:62 * px];
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginButton addTarget:self action:@selector(RegisterClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginButton];
    
    UILabel * PromptLable = [[UILabel alloc] init];
    UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:SmallFont];
    NSString * str = @"新用户登录时将自动注册且表示您已同意";
    PromptLable.font = fnt;
    CGSize PromptLableSize = [str sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
    PromptLable.text = str;
    PromptLable.textColor = WYCRGBColor(157, 157, 157);
    PromptLable.frame = CGRectMake(0, loginButton.frame.size.height+loginButton.frame.origin.y+20, ScreenWidth, PromptLableSize.height);
    PromptLable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:PromptLable];
    
    
    
    //用户须知的按钮
    UIButton * userAgreement = [[UIButton alloc] init];
    [userAgreement setTitle:@"《服务条款和隐私政策》" forState:UIControlStateNormal];
    userAgreement.titleLabel.font = [UIFont systemFontOfSize:43 * px];
    userAgreement.frame = CGRectMake(ScreenWidth/2-75, PromptLable.y+30,  150, PromptLable.height);
    [userAgreement addTarget:self action:@selector(pressAgree) forControlEvents:UIControlEventTouchUpInside];
    userAgreement.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [userAgreement setTitleColor:wycMain forState:UIControlStateNormal];
    [self.view addSubview:userAgreement];
    
}
-(void)pressAgree
{
    WYCArgeeViewController  *agree = [[WYCArgeeViewController alloc]init];
    agree.flag = @"333";
    [self presentViewController:agree animated:YES completion:nil];
}
//键盘回收
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_UserTextField resignFirstResponder];
    [_codeTexField resignFirstResponder];
    [_passtexfield resignFirstResponder];
    [_Zpasstexfield resignFirstResponder];
}
#pragma make ------>>获取验证码
- (void)countDownBtnAction:(UIButton *)button
{
    WYCLog(@"----------%@",self.UserTextField.text);
    WYCLogFunc;
    if (self.UserTextField.text.length == 0) {
        
        NSString * showStr = @"手机号不能为空";
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:showStr];
        return;
    }else{
        [button startWithTime:59 title:@"点击重新获取" countDownTitle:@"s后重新获取" mainColor:[UIColor colorWithRed:0 / 255.0 green:0 / 255.0 blue:0 / 255.0 alpha:0] countColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0]];
        NSString * httpsStr = [NSString stringWithFormat:@"%@mobile=%@&type=%@",Rcode,self.UserTextField.text,Ucodekey];
        
        [HttpTool POST:httpsStr params:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            
            if ([[responseObject objectForKey:@"code"] intValue] == 0) {
                
                [SVProgressHUD showImage:[UIImage imageNamed:@""] status:msgStr];
                
            }else{
                
                [SVProgressHUD showImage:[UIImage imageNamed:@""] status:msgStr];
            }
            
        } fail:^(NSURLSessionDataTask *task, NSError *error) {
            
        }];
        
    }
}

#pragma make ------>>注册按钮
- (void)RegisterClick {
    WYCLogFunc;
    
     //手机号判断是否为空
    if(self.UserTextField.text.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"手机号不能为空"];
        return;
    }
    //验证码判断是否为空
    if(self.codeTexField.text.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"请输入验证码"];
        return;
    }
    if(self.passtexfield.text.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"密码不能为空"];
        return;
    }
    if(self.Zpasstexfield.text.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"密码不能为空"];
        return;
    }
    
    if (![self.passtexfield.text isEqualToString:self.Zpasstexfield.text]) {
        [self showToast:@"两次密码不一致"];
        return;
    }

    if (self.Rgscodefield.text.length == 0) {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"邀请码不能为空"];
        return;
    }
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    NSString * passStr = [NSString stringWithFormat:@"%@",self.passtexfield.text];
    NSString *pas = [RSAUtil encryptString:passStr publicKey:RSA_P_KEY];
    params[@"mobile"] = self.UserTextField.text;
    params[@"password"] = pas;
    params[@"authcode"] = self.codeTexField.text;
    params[@"regCode"] = self.Rgscodefield.text;
    NSLog(@"传的数据%@",params);
    [HttpTool POST:Register params:params success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([[responseObject objectForKey:@"code"] intValue] == 0) {
            NSDictionary * dict = [responseObject objectForKey:@"result"];
            WYCRealnameController * authen = [[WYCRealnameController alloc] init];
            [self presentViewController:authen animated:NO completion:nil];
//            [self.navigationController pushViewController:authen animated:YES];
            WYCAccount * Account = [[WYCAccount alloc] initWithDic:dict];
    
            [WYCAccountTool saveAccount:Account];
    
            [WYCIsAppLoginTool saveIsAppLogin:YES];
        }else{
            
            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:msgStr];
        }

    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:Failed];
    }];

}
- (void)rgscodeButtonClick{
    WYCLogFunc;
    QRScanViewController *vc = [[QRScanViewController alloc] init];
    vc.delegate = self;
    vc.hidesBottomBarWhenPushed = YES;
    [self showViewController:vc sender:nil];
    
}
- (void)passtexfieldButtonClick{
    self.passtexfieldButton.selected = !self.passtexfieldButton.selected;
    if (self.passtexfieldButton.selected == YES) {
        self.passtexfield.secureTextEntry = NO;
    }else{
        
        self.passtexfield.secureTextEntry = YES;
    }
    
}

- (void)ZpasstexfieldButtonClick{
    self.ZpasstexfieldButton.selected = !self.ZpasstexfieldButton.selected;
    if (self.Zpasstexfield.selected == YES) {
        self.Zpasstexfield.secureTextEntry = NO;
    }else{
        
        self.Zpasstexfield.secureTextEntry = YES;
    }
    
}
- (void)qrScanResult:(NSString *)result viewController:(QRScanViewController *)qrScanVC
{
    
    [qrScanVC dismissViewControllerAnimated:NO completion:nil];
    
    self.Rgscodefield.text = result;
}
- (void)usertexfieldButtonClick{
    
    self.UserTextField.text = @"";
}
-(BOOL)validateMobile:(NSString *)mobileNum
{
    NSString *regex = @"^[1]([3-8]{1}[0-9]{1}|59|58|88|89)[0-9]{8}";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:mobileNum];
    
    return isMatch;
}
#pragma make ------>>返回按钮
- (void)backClick
{
    [self dismissViewControllerAnimated:NO completion:nil];
    
}

@end
